package com.core.sdk.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class NetworkUtil {
	private static final String TAG = NetworkUtil.class.getSimpleName();
	
	@Inject
	private ConnectivityManager connectivityManager;

	/** 检查网络是否畅通 */
	public boolean isAvailable() {
		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null)
			return false;
		return info.isConnected();
	}

	/** 判断当前网络是否为wifi */
	public boolean isWifi() {
		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		return info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
	}
	
	/** 判断当前网络是否为GPRS */
	public boolean isGPRS() {
		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		return info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE;
	}

	/** 通过蓝牙获取MAC地址 */
	public String getLocalMacAddressFromBluetooth() {
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		String macAddress = null;
		if (bluetoothAdapter != null)
			macAddress = bluetoothAdapter.getAddress();
		return macAddress;
	}

	/** 通过WIFI获取MAC地址 */
	public String getLocalMacAddressFromWifi(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		String macAddress = null;
		if (info != null)
			macAddress = info.getMacAddress();
		return macAddress;
	}

	/** 获取IP地址 */
	public String getLocalIpAddress() {
		String ipAddress = null;
		try {
			Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					String ip = inetAddress.getHostAddress().toString();
					if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip)) {
						ipAddress = ip;
						break;
					}
				}
				if (ipAddress != null)
					break;
			}
		} catch (Exception ex) {
			Log.e(TAG, "can't get ip Address", ex);
		}
		return ipAddress;
	}
}
